import os
import pandas as pd
import requests
from pathlib import Path


def upload_file(file_biz_type, file_path, file_name, index, upload_url):
    """
    上传文件到指定URL

    参数:
        file_path: 文件路径
        upload_url: 上传接口URL

    返回:
        上传成功后的URL,失败返回None
    """
    # 请求体参数
    data = {
        "bizType": str(file_biz_type),
        "fileDir": str(file_biz_type)+"/2025/10/19/"+str(index).zfill(3),
        "fileData": open(file_path, "rb")
    }
    # 构造 multipart/form-data 的文件部分
    files = {
        "fileData": (file_name.strip(), open(file_path, "rb"), "application/octet-stream")
    }
    try:
        # 发起 POST 请求
        response = requests.post(upload_url, files=files, data=data)
        # 检查响应状态码
        if response.status_code == 200:
            # 解析 JSON 响应
            response_json = response.json()
            print(response_json)
            # 检查 success 字段
            if response_json.get("success", False):
                # 提取 data 中的 filePath
                file_path = response_json.get("data", {}).get("filePath")
                print(f"请求成功，filePath: {file_path}")
                return file_path
            else:
                print(f"请求失败，错误信息: {response_json.get('msg', '未知错误')}")
        else:
            print(f"请求失败，状态码: {response.status_code}, 响应: {response.text}")

    except requests.exceptions.RequestException as e:
        print(f"请求发生错误: {e}")

    finally:
        # 关闭文件
        # if "fileData" in files:
        #     files["fileData"].close()
        print("success")


def process_files_and_excel(folder_path, excel_path, business_type_column='业务类型',
                            url_column='图标url', upload_url='YOUR_UPLOAD_API_URL', file_biz_type=1674):
    """
    遍历文件夹,匹配Excel中的业务类型,上传文件并回写URL

    参数:
        folder_path: 文件夹路径
        excel_path: Excel文件路径
        business_type_column: 业务类型列名
        url_column: 图标URL列名
        upload_url: 上传接口URL
    """

    # 读取Excel
    try:
        df = pd.read_excel(excel_path)
    except Exception as e:
        print(f"读取Excel失败: {str(e)}")
        return

    # 检查列是否存在
    if business_type_column not in df.columns:
        print(f"Excel中不存在'{business_type_column}'列")
        return

    # 如果URL列不存在,创建它
    if url_column not in df.columns:
        df[url_column] = ''

    df[url_column] = df[url_column].astype(str).replace('nan', '')

    # 获取所有业务类型
    business_types = df[business_type_column].dropna().unique()
    print(f"找到 {len(business_types)} 个业务类型")

    # 遍历文件夹中的所有文件
    folder = Path(folder_path)
    if not folder.exists():
        print(f"文件夹不存在: {folder_path}")
        return

    uploaded_count = 0

    # 遍历文件夹中的文件
    i = 1
    for file_path in folder.rglob('*'):
        if file_path.is_file():
            filename = file_path.name

            # 检查文件名是否包含任何业务类型
            for business_type in business_types:
                business_type_str = str(business_type)

                if business_type_str in filename:
                    print(f"\n匹配到文件: {filename} -> 业务类型: {business_type_str}")

                    # 上传文件
                    uploaded_url = upload_file(file_biz_type, str(file_path), filename, i, upload_url)

                    if uploaded_url:
                        # 回写到Excel中所有匹配该业务类型的行

                        mask = df[business_type_column] == business_type
                        df.loc[mask, url_column] = uploaded_url
                        uploaded_count += 1
                        print(f"上传成功,URL: {uploaded_url}")

                    # 找到匹配后跳出循环,避免重复处理
                    break

    # 保存更新后的Excel
    try:
        df.to_excel(excel_path, index=False)
        print(f"\n处理完成! 共上传 {uploaded_count} 个文件")
        print(f"Excel已更新: {excel_path}")
    except Exception as e:
        print(f"保存Excel失败: {str(e)}")


# 使用示例
if __name__ == "__main__":
    # 配置参数
    FOLDER_PATH = "D:\\project_file\\app我的优化\\我的页面icon"  # 图片文件夹路径
    EXCEL_PATH = "D:\\project_file\\app我的优化\\生产-icon表格完善.xlsx"  # Excel文件路径
    UPLOAD_URL = "http://filegateway.ewt360.com/api/filecenter/fileService/saveFile"  # 上传接口URL

    # 执行处理
    process_files_and_excel(
        folder_path=FOLDER_PATH,
        excel_path=EXCEL_PATH,
        business_type_column='业务类型',  # Excel中的业务类型列名
        url_column='图标url',  # Excel中的URL列名
        upload_url=UPLOAD_URL,
        file_biz_type=1056
    )